package client.comm.baoding.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.api.bean.MeCoupon
import client.comm.baoding.api.bean.ShopingBean
import client.comm.baoding.api.bean.SuccessEvent
import client.comm.baoding.api.bean.UserAddress
import client.comm.baoding.databinding.ActivityConfirmorderBinding
import client.comm.baoding.databinding.LayoutConfirmenterorderitemBinding
import client.comm.baoding.dialog.SelectPayTypeDialog
import client.comm.baoding.ui.vm.ConfirmOrderModel
import client.comm.commlib.dialog.ValidatePwdDialog
import client.comm.commlib.toast.toast
import client.comm.commlib.widget.EmptyLayout
//import com.pay.paytypelibrary.base.OnPayResultListener
//import com.pay.paytypelibrary.base.OrderInfo
//import com.pay.paytypelibrary.base.PayUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal

class ConfirmOrderActivity :
    BaseMiddleActivity<ConfirmOrderModel, ActivityConfirmorderBinding>() {

    var tradeNo: String = "" //订单编号

    override fun getLayout(): Int {
        return R.layout.activity_confirmorder
    }

    val s = "ccsdgsdgs"

    val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                if (it.action.equals(s)) {
                    finish()
                }
            }
        }

    }

    override fun initView() {
        EventBus.getDefault().register(this)
        binding?.apply {
            event = this@ConfirmOrderActivity
            vm = viewModel
            emptyLayout.setOnClickListener {
                viewModel.userInfo()
            }
        }

        registerReceiver(broadcastReceiver, IntentFilter(s))
    }


    override fun observerUI() {
        viewModel.userRet.observe(this, {

            it?.let {
                if (it.isSuccess) {

                    binding.emptyLayout.visibility = View.GONE
                    binding.user = it.data
                    viewModel.payTypeTxt.value = "余额支付(余额:${it.data!!.income})"
//                    viewModel.payType.value = 1

                    it.data?.address_list?.let {
                        if (it.size > 0)
                            binding.addr = it[0]
                    }
                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        viewModel.commitRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    if (it.data!!.pay_type.equals("3")) {//支付宝支付
                        tradeNo = it.data!!.trade_no
//                        AlipayUtils(this).pay(it.data!!.pay_url)

//                        PayUtil.CashierPaySingle(
//                            this,
//                            it.data!!.pay_data,
//                            object : OnPayResultListener {
//                                override fun onSuccess(orderInfo: OrderInfo) {
//                                    Log.d("ddd", "CashierPaySingleonSuccess")
//                                }
//                                override fun onError(retMsg: String) {
//                                    toast(retMsg)
//                                }
//                            })
                    } else if (it.data!!.pay_type.equals("5") || it.data!!.pay_type.equals("4")) {
                        val intent = Intent(this@ConfirmOrderActivity, WebPayActivity::class.java)
                            .apply {
                                putExtra("adInfo", it.data!!.pay_url)
                                putExtra("title", "支付")
                            }
                        startActivityForResult(intent, 0x999)
                    } else {
                        startActivity(Intent(this, GoodsOrderActivity::class.java).apply {
                            putExtra("index", 2)
                        })
                        finish()
                        toast("下单成功")
                    }
                } else {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                }
            }
        })
        viewModel.checkOrderPayCall.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("支付成功")
                    finish()
                } else {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
//                    toast(it.message)
                }
            }
        })

        viewModel.userInfo()
    }

    override fun initViewModel(): ConfirmOrderModel = createViewModel()

    override fun initData() {
        val list = intent.getParcelableArrayListExtra<ShopingBean>("list")
        list?.let {
            binding.goodsWrap.removeAllViews()
            for (data in it) {
                val bindingType =
                    DataBindingUtil.inflate<LayoutConfirmenterorderitemBinding>(
                        LayoutInflater.from(this),
                        R.layout.layout_confirmenterorderitem,
                        binding.goodsWrap,
                        false
                    ).apply {
                        this.bean = data
                        mImgLoader.load(data.goods_img).into(img)

                        commPriceIntegral.apply {
                            var is_price_show: Boolean = false
                            var is_integral_unit_show: Boolean = false

                            if (data.price > 0) {
                                tvPrice.text = "${data.price}"
                                is_price_show = true


                            } else {
                                tvPrice.text = ""
                                is_price_show = false

                            }

                            if (is_price_show) {
                                tvPriceUnit.visibility = View.VISIBLE
                            } else {
                                tvPriceUnit.visibility = View.GONE
                            }

                            if (is_integral_unit_show) {
                                tvIntegralDesc.visibility = View.VISIBLE
                            } else {
                                tvIntegralDesc.visibility = View.GONE
                            }

                            tvPrice.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)
                            tvIntegral.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)

                            tvPriceUnit.setTextColor(resources!!.getColor(R.color.txt_color))
                            tvPrice.setTextColor(resources!!.getColor(R.color.txt_color))
                            tvIntegral.setTextColor(resources!!.getColor(R.color.txt_color))
                            tvIntegralDesc.setTextColor(resources!!.getColor(R.color.txt_color))
                        }

                    }
                binding.goodsWrap.addView(bindingType.root)
            }
            updatePrice()
        }
    }

//    var lpq_price_total: Double = 0.0

    fun updatePrice() {
        var number: BigDecimal = BigDecimal(0)
//        var lpq_price_new: BigDecimal = BigDecimal(0)
        var integral: BigDecimal = BigDecimal(0)
//        var integral_f: BigDecimal = BigDecimal(0)
        val items = intent.getParcelableArrayListExtra<ShopingBean>("list")
        items?.let {
            for (b in items) {
                b?.let {
                    number = number.add(BigDecimal(b.num).multiply(BigDecimal(b.price)))
                    if (b.integral > 0)
                        integral =
                            integral.add(BigDecimal(b.num).multiply(BigDecimal(b.integral)))
                }
            }
        }
        binding.coupon?.let {
            number = number.subtract(BigDecimal(it.minus_price))
        }

        binding.incGoodsList.apply {
            this.price = "${number.toDouble()}"
            this.integral = "${integral.toDouble()}"
        }
        binding.price = "${number.toDouble()}"
        binding.integral = "${integral.toDouble()}"

        binding.commPriceIntegral.apply {
            var is_price_show: Boolean = false
            var is_integral_unit_show: Boolean = false

            var integral = integral.toDouble()
            var price = number.toDouble()
//            var lpqPrice = lpq_price_new.toDouble()
            if (price > 0) {
                tvPrice.text = "${price}"
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            } else {
                tvPrice.text = ""
                is_price_show = false
                if (integral > 0) {
                    tvIntegral.text = "" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            }

            if (is_price_show) {
                tvPriceUnit.visibility = View.VISIBLE
            } else {
                tvPriceUnit.visibility = View.GONE
                binding.incGoodsList.rlGoodAccount.visibility = View.GONE
            }

            if (is_integral_unit_show) {
                tvIntegralDesc.visibility = View.VISIBLE
            } else {
                tvIntegralDesc.visibility = View.GONE
            }
        }

        binding.commPriceIntegral1.apply {
            var is_price_show: Boolean = false
            var is_integral_unit_show: Boolean = false

            var integral = integral.toDouble()
            var price = number.toDouble()

            if (price > 0) {
                tvPrice.text = "${price}"
                is_price_show = true
                if (integral > 0) {
                    tvIntegral.text = "+" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            } else {
                tvPrice.text = ""
                is_price_show = false
                if (integral > 0) {
                    tvIntegral.text = "" + integral //+ "积分"
                    is_integral_unit_show = true
                } else {
                    tvIntegral.text = ""
                    is_integral_unit_show = false
                }
            }


            if (is_price_show) {
                tvPriceUnit.visibility = View.VISIBLE
            } else {
                tvPriceUnit.visibility = View.GONE
            }

            if (is_integral_unit_show) {
                tvIntegralDesc.visibility = View.VISIBLE
            } else {
                tvIntegralDesc.visibility = View.GONE
            }
        }

    }

    fun ok() {
        if (binding.addr == null) {
            toast("请选择地址")
            return
        }

        selectPayType()

    }

    fun selectAddr() {
        startActivityForResult(Intent(this, AddrMangerActivity::class.java).apply {
            putExtra("select", true)
        }, 0x11)
    }

    fun selectCoupon() {
        startActivityForResult(Intent(this, MeCouponActivity::class.java).apply {
            putExtra("select", true)
            putExtra("price", binding.price!!.toDouble())
        }, 0x12)
    }

    fun selectPayType() {
        SelectPayTypeDialog(this).apply {
//            good_wallet_pin.set(lpq_price_total)//设置体验券金额

            one = { it, txt ->
                viewModel.payType.value = it
                viewModel.payTypeTxt.value = txt

//                toast("${viewModel.payType.value}")
                val list = intent.getParcelableArrayListExtra<ShopingBean>("list")
                var user_coupons_id = ""
                this@ConfirmOrderActivity.binding.coupon?.let {
                    user_coupons_id = it.user_coupons_id
                }

                when (viewModel.payType.value) {

                    3 -> {
                        viewModel.commitOrder(
                            list as ArrayList<ShopingBean>,
                            this@ConfirmOrderActivity.binding.addr!!.address_id,
                            user_coupons_id
                        )
                    }

                    5 -> {
                        viewModel.commitOrder(
                            list as ArrayList<ShopingBean>,
                            this@ConfirmOrderActivity.binding.addr!!.address_id,
                            user_coupons_id
                        )
                    }

                    4 -> {
                        viewModel.commitOrder(
                            list as ArrayList<ShopingBean>,
                            this@ConfirmOrderActivity.binding.addr!!.address_id,
                            user_coupons_id
                        )
                    }

                    -1 -> {

                        startActivity(
                            Intent(
                                this@ConfirmOrderActivity,
                                PayOrderUpimgActivity::class.java
                            ).apply {
                                val list = intent.getParcelableArrayListExtra<ShopingBean>("list")
                                putExtra("list", list)
                                putExtra("addr", this@ConfirmOrderActivity.binding.addr)
                            })
                    }

                    else -> {

                        ValidatePwdDialog(this@ConfirmOrderActivity).apply {
                            title = "需要验证支付密码"
                            ok = {
                                viewModel.commitOrderByPayPwdValid(
                                    it,
                                    list as ArrayList<ShopingBean>,
                                    this@ConfirmOrderActivity.binding.addr!!.address_id,
                                    user_coupons_id
                                )

                            }

                        }.show()
                    }
                }


            }
        }.show()
    }

    //支付成功的回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun paySuccess(event: SuccessEvent?) {
        viewModel.check_order_pay(tradeNo)

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            0x11 -> {
                if (resultCode == RESULT_OK) {
                    data?.let {
                        val addr = it.getSerializableExtra("address") as UserAddress.Address?
                        addr?.let {
                            binding.addr = it
                        }
                    }
                }
            }

            0x12 -> {
                if (resultCode == RESULT_OK) {
                    data?.let {
                        val addr = it.getSerializableExtra("coupon") as MeCoupon.Coupons?
                        addr?.let {
                            binding.coupon = it
                            updatePrice()
                        }
                    }
                }
            }

            0x999 -> {
                startActivity(Intent(this, GoodsOrderActivity::class.java).apply {
                    putExtra("index", 0)
                })
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        unregisterReceiver(broadcastReceiver)
    }

}